package com.visikard.ui.fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.visikard.application.Constant;
import com.visikard.application.UIMessage;
import com.visikard.application.VKRegApplication;
import com.visikard.asynctask.BaseTask;
import com.visikard.asynctask.GetTransactionHistoryNewTask;
import com.visikard.item.ItemTransactionHistory;
import com.visikard.item.NewItemTransactionHistory;
import com.visikard.ui.R;
import com.visikard.ui.activity.MerchantHomeActivity;
import com.visikard.ui.activity.RedemptionActivity;
import com.visikard.ui.activity.RedemptionActivity.RedeemptionActivityEnum;
import com.visikard.ui.activity.TransactionDetailActivity;
import com.visikard.ui.adapter.NewTransactionHistoryAdapter;
import com.visikard.ui.fragment.HistoryDateOptionFragment.IHistoryDateOption;
import com.visikard.ui.fragment.HistoryOptionFragment.IHistoryOption;
import com.visikard.utility.Utils;

public class RedeemNowFragment extends BaseFragment implements IHistoryOption, IHistoryDateOption {

	public static final String TAG_REDEEM_NOW_FRAG = "vkreg_redeem_now_fragment";
	public static final int ID_CONTAIN = R.id.main_content;

	private View typeContainer, scanContainer;
	private TextView txtFilter, txtDateFilter, txtSelectedDate;
	private View imgFilter, imgDateFilter;
	private View imgBack;

	private ListView listTransactions;
	private NewTransactionHistoryAdapter mAdapter;
	private List<NewItemTransactionHistory> mListData;

	private int pageIndex = 1;
	private boolean isNoLoadMore = false;
	private boolean isLoadingMore = false;

	private Date mCurentBackDate, mCurentNextDate;
	private SimpleDateFormat mServerDateFormat = new SimpleDateFormat(Constant.TIME_FORMAT_STR_US_DATE);
	private SimpleDateFormat mDisplayDateFormat1 = new SimpleDateFormat(Constant.TIME_FORMAT_STR_FULLMONTH_DATE);
	private SimpleDateFormat mDisplayDateFormat2 = new SimpleDateFormat(Constant.TIME_FORMAT_STR_JUST_DATE);

	private int mTxType;
	private int mDateOptionType;
	private String mTimezone;

	private Context mContext;

	private BaseTask mAsyncTask;
	private boolean mIsReloadHistory;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.redeem_now_fragment, container, false);

		typeContainer = view.findViewById(R.id.right_container);
		scanContainer = view.findViewById(R.id.left_container);
		txtFilter = (TextView) view.findViewById(R.id.txt_filter);
		imgFilter = view.findViewById(R.id.img_arrow);
		imgBack = view.findViewById(R.id.img_back);
		listTransactions = (ListView) view.findViewById(R.id.list_transactions);
		txtDateFilter = (TextView) view.findViewById(R.id.txt_date_filter);
		imgDateFilter = view.findViewById(R.id.img_arrow_left);
		txtSelectedDate = (TextView) view.findViewById(R.id.txt_selected_date);

		imgBack.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				doBackPressed();
			}
		});

		typeContainer.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				doTypeClicked();
			}
		});

		scanContainer.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				doScanClicked();
			}
		});

		txtFilter.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				doTransactionFilterClicked();
			}
		});

		imgFilter.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				doTransactionFilterClicked();
			}
		});

		txtDateFilter.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				doDateFilterClicked();
			}
		});

		imgDateFilter.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				doDateFilterClicked();
			}
		});

		mListData = new ArrayList<NewItemTransactionHistory>();
		mAdapter = new NewTransactionHistoryAdapter(getActivity(), mListData);
		listTransactions.setAdapter(mAdapter);

		listTransactions.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				doTransactionItemClicked(mAdapter.getItem(position));
			}
		});

		listTransactions.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

				// For load more
				if (totalItemCount > 2 && firstVisibleItem + visibleItemCount >= totalItemCount && !isLoadingMore
						&& !isNoLoadMore) {
					pageIndex++;
					isLoadingMore = true;
					getListTrasaction();
				}
			}
		});

		return view;
	}

	@Override
	public void onResume() {
		super.onResume();

		if (mIsReloadHistory) {
			mListData.clear();
			pageIndex = 1;
			getListTrasaction();
			mIsReloadHistory = false;
		}
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		txtDateFilter.setText(getString(R.string.txt_today));
		mCurentBackDate = Utils.getDate(0);
		mCurentNextDate = Utils.getDate(0);
		mDateOptionType = HistoryDateOptionFragment.TODAY;
		mTimezone = Utils.getTimeZoneString();
		txtSelectedDate.setText(mDisplayDateFormat1.format(mCurentBackDate));
		getListTrasaction();
	}

	private void getListTrasaction() {
		mAsyncTask = new GetTransactionHistoryNewTask(mHandler);

		// add time zone to server
		String searchBackDate = mServerDateFormat.format(mCurentBackDate);
		String searchNextDate = mServerDateFormat.format(mCurentNextDate);

		mAsyncTask.execute(VKRegApplication.uid, Constant.BOOLEAN_FALSE, mTxType, searchBackDate, searchNextDate,
				mTimezone, pageIndex, VKRegApplication.mPageSize);
	}

	protected void doTransactionItemClicked(NewItemTransactionHistory item) {
		Bundle bundle = new Bundle();
		ItemTransactionHistory _item = new ItemTransactionHistory();
		if (item instanceof ItemTransactionHistory)
			_item = (ItemTransactionHistory) item;
		bundle.putParcelable(TransactionDetailActivity.EXTRA_ITEM_TARGET, _item);
		Intent intent = new Intent(getActivity(), TransactionDetailActivity.class);
		intent.putExtras(bundle);
		startActivity(intent);

	}

	protected void doBackPressed() {
		((MerchantHomeActivity) getActivity()).setHomeContent(new MerchantHomeFragment(), false,
				SlidingMenu.TOUCHMODE_MARGIN);
	}

	protected void doTransactionFilterClicked() {
		FragmentTransaction ft = getFragmentManager().beginTransaction();
		Fragment prev = getFragmentManager().findFragmentByTag("dialog");
		if (prev != null) {
			ft.remove(prev);
		}
		ft.addToBackStack(null);

		// Create and show the dialog.
		HistoryOptionFragment newFragment = new HistoryOptionFragment();
		newFragment.setListener(this);
		Bundle args = new Bundle();
		int selectedOption = HistoryOptionFragment.ALL_TRANSACTION;
		switch (mTxType) {
			case ItemTransactionHistory.TYPE_ALL_TRANS:
				break;
			case ItemTransactionHistory.TYPE_COUPON:
				selectedOption = HistoryOptionFragment.COUPON_ONLY;
				break;
			case ItemTransactionHistory.TYPE_FREESTUFF:
				selectedOption = HistoryOptionFragment.FREESTUFF_ONLY;
				break;
			case ItemTransactionHistory.TYPE_GIFTKARD:
				selectedOption = HistoryOptionFragment.GIFTKARD_ONLY;
				break;
			case ItemTransactionHistory.TYPE_PRODUCT:
				selectedOption = HistoryOptionFragment.PRODUCT_ONLY;
				break;
			case ItemTransactionHistory.TYPE_PUNCHKARD:
				selectedOption = HistoryOptionFragment.PUNCHKARD_ONLY;
				break;
			case ItemTransactionHistory.TYPE_RTUI_COUPON:
				selectedOption = HistoryOptionFragment.RTUI_COUPON_ONLY;
				break;
		}
		args.putInt(HistoryOptionFragment.KEY_SELECTED_OPTION, selectedOption);
		newFragment.setArguments(args);
		newFragment.show(ft, "dialog");

	}

	protected void doDateFilterClicked() {
		FragmentTransaction ft = getFragmentManager().beginTransaction();
		Fragment prev = getFragmentManager().findFragmentByTag("dialog");
		if (prev != null) {
			ft.remove(prev);
		}
		ft.addToBackStack(null);

		// Create and show the dialog.
		HistoryDateOptionFragment newFragment = new HistoryDateOptionFragment();
		newFragment.setListener(this);
		Bundle args = new Bundle();
		args.putInt(HistoryDateOptionFragment.KEY_SELECTED_OPTION, mDateOptionType);
		if (mDateOptionType == HistoryDateOptionFragment.DATE_RANGE) {
			args.putLong(HistoryDateOptionFragment.KEY_START_DATE, mCurentBackDate.getTime());
			args.putLong(HistoryDateOptionFragment.KEY_END_DATE, mCurentNextDate.getTime());
		}
		newFragment.setArguments(args);
		newFragment.show(ft, "dialog");
	}

	protected void doScanClicked() {
		// Fragment reddemScanFrag = new RedeemScanFragment();
		// FragmentTransaction fTrans = getActivity().getSupportFragmentManager().beginTransaction();
		// fTrans.replace(ID_CONTAIN, reddemScanFrag).addToBackStack(TAG_REDEEM_NOW_FRAG).commit();
		Intent intent = new Intent(getActivity(), RedemptionActivity.class);
		intent.putExtra(RedemptionActivity.KEY_STARTUP_FRAGMENT, RedeemptionActivityEnum.SCANCODE);
		startActivity(intent);
		mIsReloadHistory = true;
	}

	protected void doTypeClicked() {
		// Fragment redeemTypingFrag = new RedeemTypingFragment();
		// getActivity().getSupportFragmentManager().beginTransaction().replace(ID_CONTAIN, redeemTypingFrag)
		// .addToBackStack(TAG_REDEEM_NOW_FRAG).commit();
		Intent intent = new Intent(getActivity(), RedemptionActivity.class);
		intent.putExtra(RedemptionActivity.KEY_STARTUP_FRAGMENT, RedeemptionActivityEnum.TYPECODE);
		startActivity(intent);
		mIsReloadHistory = true;
	}

	@Override
	public void onHistoryOptionDone(boolean[] options) {
		int selected = 0;
		for (; selected < options.length; selected++)
			if (options[selected])
				break;
		String text = "";
		int txType = mTxType;
		switch (selected) {
			case HistoryOptionFragment.ALL_TRANSACTION:
				text = getString(R.string.txt_all_transaction);
				txType = ItemTransactionHistory.TYPE_ALL_TRANS;
				break;
			case HistoryOptionFragment.COUPON_ONLY:
				text = getString(R.string.txt_coupon_only);
				txType = ItemTransactionHistory.TYPE_COUPON;
				break;
			case HistoryOptionFragment.FREESTUFF_ONLY:
				text = getString(R.string.txt_free_stuff_only);
				txType = ItemTransactionHistory.TYPE_FREESTUFF;
				break;
			case HistoryOptionFragment.GIFTKARD_ONLY:
				text = getString(R.string.txt_giftkard_only);
				txType = ItemTransactionHistory.TYPE_GIFTKARD;
				break;
			case HistoryOptionFragment.PRODUCT_ONLY:
				text = getString(R.string.txt_product_only);
				txType = ItemTransactionHistory.TYPE_PRODUCT;
				break;
			case HistoryOptionFragment.PUNCHKARD_ONLY:
				text = getString(R.string.txt_punchkard_only);
				txType = ItemTransactionHistory.TYPE_PUNCHKARD;
				break;
			case HistoryOptionFragment.RTUI_COUPON_ONLY:
				text = getString(R.string.txt_rtui_coupon_only);
				txType = ItemTransactionHistory.TYPE_RTUI_COUPON;
				break;
		}

		if (txType != mTxType) {
			mTxType = txType;
			txtFilter.setText(text);
			mListData.clear();
			pageIndex = 1;
			getListTrasaction();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
			case UIMessage.MSG_GET_LIST_SUCCESS:
				List<ItemTransactionHistory> listResults = (ArrayList<ItemTransactionHistory>) msg.obj;
				mListData.addAll(listResults);
				if (!isLoadingMore) {
					if (mListData.size() < VKRegApplication.mPageSize)
						isNoLoadMore = true;
				}
				mAdapter.notifyDataSetChanged();
				isLoadingMore = false;
				return true;
		}
		return super.handleMessage(msg);
	}

	@Override
	public void onHistoryDateOptionDone(int options, Date from, Date to) {
		Date fromDate = null, toDate = null;
		switch (options) {
			case HistoryDateOptionFragment.TODAY:
				txtDateFilter.setText(getString(R.string.txt_today));
				fromDate = Utils.getDate(0);
				toDate = Utils.getDate(0);
				mDateOptionType = HistoryDateOptionFragment.TODAY;
				txtSelectedDate.setText(mDisplayDateFormat1.format(fromDate));
				break;
			case HistoryDateOptionFragment.LAST_3_DAYS:
				txtDateFilter.setText(getString(R.string.txt_last_3_day));
				fromDate = Utils.getDate(-3);
				toDate = Utils.getDate(0);
				mDateOptionType = HistoryDateOptionFragment.LAST_3_DAYS;
				txtSelectedDate.setText(String.format(getString(R.string.txt_from_date_to_date),
						mDisplayDateFormat2.format(fromDate), mDisplayDateFormat2.format(toDate)));
				break;
			case HistoryDateOptionFragment.LAST_5_DAYS:
				txtDateFilter.setText(getString(R.string.txt_last_5_day));
				fromDate = Utils.getDate(-5);
				toDate = Utils.getDate(0);
				mDateOptionType = HistoryDateOptionFragment.LAST_5_DAYS;
				txtSelectedDate.setText(String.format(getString(R.string.txt_from_date_to_date),
						mDisplayDateFormat2.format(fromDate), mDisplayDateFormat2.format(toDate)));
				break;
			case HistoryDateOptionFragment.DATE_RANGE:
				txtDateFilter.setText(getString(R.string.txt_date_range));
				fromDate = from;
				toDate = to;
				mDateOptionType = HistoryDateOptionFragment.DATE_RANGE;
				txtSelectedDate.setText(String.format(getString(R.string.txt_from_date_to_date),
						mDisplayDateFormat2.format(fromDate), mDisplayDateFormat2.format(toDate)));
				break;
		}

		if (fromDate != null
				&& toDate != null
				&& (Utils.compareDateOnly(fromDate, mCurentBackDate) != 0 || Utils.compareDateOnly(toDate,
						mCurentNextDate) != 0)) {
			mCurentBackDate = fromDate;
			mCurentNextDate = toDate;
			mListData.clear();
			pageIndex = 1;
			getListTrasaction();
		}

	}

}
